<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏房间</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_room.css">
</head>

<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen"> 等待玩家连接中... </div>
        </div>
        <div id="chat_area" width="400px" height="300px">
            <div id="chat_show">
                <p id="self_msg">你好！</p></br>
                <p id="peer_msg">你好！</p></br>
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>
    <script>

        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);//websocket的句柄
        var room_infor_json;
        var isblack;
        var iswhite;
        var isme;
        var game_isover=false;
        window.onbeforeunload = function () {
            ws_hdl.close();
        }
        ws_hdl.onopen = function () {
            console.log("房间长连接建立成功");
        }
        ws_hdl.onclose = function () {
            console.log("房间长连接断开");
        }
        ws_hdl.onerror = function () {
            console.log("房间长连接出错");
        }
        function set_screen(is_me) {
            var screen_hdl = document.getElementById("screen");
            if (is_me) {
                screen_hdl.innerHTML = "轮到己方走棋...";

            } else {
                screen_hdl.innerHTML = "轮到对方走棋...";
            }
        }
        var chat_div = document.getElementById("chat_button");
        chat_div.onclick = function () {
            var sed_msg = {
                optype: "chat",
                room_id: room_infor_json.room_id,
                uid: room_infor_json.uid,
                message: document.getElementById("chat_input").value
            };
            ws_hdl.send(JSON.stringify(sed_msg));
            document.getElementById("chat_input").value="";
        }

        ws_hdl.onmessage = function (evt) {
            var info_json = JSON.parse(evt.data);
            if (info_json.optype == "room_ready") {
                //需要初始化房间
                //判断是对方走棋还是己方走棋
                room_infor_json = JSON.parse(evt.data);
                //规定黑棋先下 如果是
                if (room_infor_json.black_id == info_json.uid) {
                    isblack = true;
                    iswhite = false;
                    isme = true;
                } else {
                    isblack = false;
                    iswhite = true;
                    isme = false;
                }
                //负责
                set_screen(isblack);
                initGame();
            } else if (info_json.optype == "put_chess") {
                if (info_json.result == false) {
                    alert(info_json.reason);
                    return;
                }
                //首先我们的点击时间触发发送下棋的请求 默认的情况下isme黑棋是true可以走
                //此时向服务器发送请求 服务器返回此时的下棋用户就是黑棋 
                isme = room_infor_json.uid == info_json.uid ? false : true;
                //判断此时应该绘制白色棋子 还是黑色的
                iswhite = room_infor_json.white_id == info_json.uid ? true : false;
                if (info_json.row != -1 && info_json.col != -1) {
                    oneStep(info_json.col, info_json.row, iswhite);
                    chessBoard[info_json.row][info_json.col] = 1;
                    set_screen(isme);
                }
                //判断此时是否有我们的胜利者
                if (info_json.winner == 0) {
                    game_isover=false;
                    return;
                }
                game_isover=true;
                //我们要跟新我们的分数并提供一个返回大厅的按钮
                var screen_div = document.getElementById("screen");
                if (room_infor_json.uid == info_json.winner) {//如果获胜的是我
                    screen_div.innerHTML = info_json.reason;
                } else {
                    screen_div.innerHTML = "你输了";
                    
                }
                //创建返回大厅的按钮
                var chess_area_div = document.getElementById("chess_area");
                var button_div = document.createElement("div");
                button_div.innerHTML = "返回大厅";
                button_div.onclick = function () {
                    ws_hdl.close();//关闭我们的房间连接
                    location.replace("/game_hall.html");//跳转到我们的游戏大厅
                    
                };
                //把创建的组件加入我们的chess_area区域
                chess_area_div.appendChild(button_div);
                return;
            } else if (info_json.optype == "chat") {
                //此时我们要进行我们的聊天
                if(info_json.result==false){//包含敏感词
                    alert(info_json.reason);
                    return;
                }
                //创建一个p标签
                var msg_div = document.createElement("p");
                msg_div.innerHTML = info_json.message;
                if(room_infor_json.uid==info_json.uid){
                    //设置id和属性
                    msg_div.setAttribute("id","self_msg");
                }else{
                    msg_div.setAttribute("id","peer_msg");
                }
                var br_div = document.createElement("br");//换行符
                //把我们的p标签加入我们的chat_show中
                var chat_show_hdl=document.getElementById("chat_show");
                chat_show_hdl.append(msg_div);
                chat_show_hdl.append(br_div);
                return;

            } else {
                location.replace("/login.html");
                return;
            }
        }




        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        //获取chess控件区域2d画布
        let context = chess.getContext('2d');
        function initGame() {
            initBoard();
            // 背景图片
            let logo = new Image();
            logo.src = "image/sky.jpeg";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }

        }
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            context.strokeStyle = "#BFBFBF";
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                //横向的线条
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430);
                context.stroke();
                //纵向的线条
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30);
                context.stroke();
            }
        }
        //绘制棋子 绘制棋子是按照坐标系下进行绘制的
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            //createLinearGradient() 方法创建放射状/圆形渐变对象
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            if(game_isover){
                alert("此时游戏已经结束");
                return;
            }
            if (!isme) {
                alert("对方正在走棋...");
                return;
            }
            let x = e.offsetX;//计算的是我们的x轴也就是第几列
            let y = e.offsetY;//计算的是我们的纵坐标也就是我们二维数组的第几行
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);//此时发送的col就是二维数组的列
            let row = Math.floor(y / 30);//二维数组的行
            if (chessBoard[row][col] != 0) {
                alert("当前位置已有棋子！");
                return;
            }
            //oneStep(col, row, iswhite);
            //发送请求 发送的是二维数组的行 列
            send_chess(row, col);
        }
        function send_chess(r, c) {
            var chess_info = {
                optype: "put_chess",
                //把当前用户所在的房间号传进去
                room_id: room_infor_json.room_id,
                //把当前下棋的用户的uid传进去
                uid: room_infor_json.uid,
                row: r,
                col: c
            };
            ws_hdl.send(JSON.stringify(chess_info));
            console.log("click:" + JSON.stringify(chess_info));
        }
        initGame();

    </script>
</body>

</html>